package com.amgl.amupush.news;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amgl.amupush.R;
import com.amgl.amupush.adapter.NewsListRVAdapter;
import com.amgl.amupush.base.BaseFragment;
import com.amgl.amupush.data.News;
import com.amgl.recyclerviewwithheaderfooter.DefaultScrollToLoadMoreListener;
import com.amgl.recyclerviewwithheaderfooter.HeaderAndFooterRecyclerViewAdapter;
import com.amgl.recyclerviewwithheaderfooter.HeaderAndFooterUtils;
import com.amgl.recyclerviewwithheaderfooter.LoadMoreListener;
import com.amgl.recyclerviewwithheaderfooter.footer.DefaultFooterView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link NewsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link NewsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsFragment extends BaseFragment implements NewsContract.NewsView {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public NewsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NewsFragment newInstance(String param1, String param2) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    NewsContract.Presenter mPresenter;

    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    LinearLayoutManager mLayoutManager;
    NewsListRVAdapter mNewsAdapter;

    HeaderAndFooterRecyclerViewAdapter mHAFAdapter;

    LoadMoreListener mLoadMoreListener = new LoadMoreListener() {
        @Override
        public void loadMore() {
            mPresenter.loadMore();
        }

        @Override
        public boolean isLastPage() {
            return mPresenter.isEndPage();
        }

        @Override
        public int getPageSize() {
            return mPresenter.getPageSize();
        }
    };

    NewsListRVAdapter.OnNewsClickListener mOnNewsClickListener = new NewsListRVAdapter.OnNewsClickListener() {
        @Override
        public void onNewsClick(int position) {
            showToast("position " + position);
        }
    };

    DefaultScrollToLoadMoreListener mScrollListener;

    DefaultFooterView mFooterView;

    View mHeaderView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_news, container, false);
        ButterKnife.bind(this, rootView);

        mHeaderView = inflater.inflate(R.layout.header_news, container, false);
        mFooterView = new DefaultFooterView(getActivity());

        setupView();

        return rootView;
    }

    private void setupView() {
        mSwipeRefreshLayout.setColorSchemeColors(
                ContextCompat.getColor(getActivity(), R.color.colorPrimary),
                ContextCompat.getColor(getActivity(), R.color.colorAccent),
                ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark)
        );
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.loadNews();
            }
        });

        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mNewsAdapter = new NewsListRVAdapter(getActivity());
        mNewsAdapter.setOnNewsClickListener(mOnNewsClickListener);

        mHAFAdapter = new HeaderAndFooterRecyclerViewAdapter(mNewsAdapter);
        mRecyclerView.setAdapter(mHAFAdapter);
        HeaderAndFooterUtils.setHeaderView(mRecyclerView, mHeaderView);
        HeaderAndFooterUtils.setFooterView(mRecyclerView, mFooterView);

        mScrollListener = new DefaultScrollToLoadMoreListener(mLoadMoreListener);
//        mScrollListener.setLoadingView(mFooterView);
        mScrollListener.setLoadingState(DefaultScrollToLoadMoreListener.STATE_IDLE);

        mRecyclerView.addOnScrollListener(mScrollListener);
    }

    @OnClick(R.id.btn_test)
    void onTestClick() {
        onButtonPressed(null);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    @Override
    public void showNewData(List<News> newsList) {
        mSwipeRefreshLayout.setRefreshing(false);

        Timber.d("show new list");

        mNewsAdapter.setDataList(newsList);
        mNewsAdapter.notifyDataSetChanged();

        mScrollListener.setLoadingState(DefaultScrollToLoadMoreListener.STATE_IDLE);
    }

    @Override
    public void showMoreData(List<News> newsList) {
        Timber.d("show more list");

        mNewsAdapter.addDataList(newsList);
        mNewsAdapter.notifyDataSetChanged();

        if (mPresenter.isEndPage()) {
            mScrollListener.setLoadingState(DefaultScrollToLoadMoreListener.STATE_END);
        } else {
            mScrollListener.setLoadingState(DefaultScrollToLoadMoreListener.STATE_IDLE);
        }
    }

    @Override
    public void isEndPage() {

    }

    @Override
    public void showError(String message) {

    }

    @Override
    public void setPresenter(NewsContract.Presenter presenter) {
        mPresenter = presenter;
    }
}
